package com.toune.movie.base.myview;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.Display;
import android.view.Gravity;
import android.view.KeyboardShortcutGroup;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.toune.movie.R;
import com.toune.movie.base.App;
import com.toune.movie.base.AppConstant;
import com.toune.movie.base.myUtil.MyUtil;
import com.toune.movie.lrc.ILrcBuilder;
import com.toune.movie.lrc.ILrcViewListener;
import com.toune.movie.lrc.impl.DefaultLrcBuilder;
import com.toune.movie.lrc.impl.LrcRow;
import com.toune.movie.lrc.impl.LrcView;
import com.toune.movie.service.MusicService;
import com.toune.movie.vo.MusicVo;
import com.vondear.rxtool.RxDataTool;
import com.vondear.rxtool.RxFileTool;
import com.vondear.rxtool.RxKeyboardTool;
import com.vondear.rxtool.RxSPTool;
import com.vondear.rxtool.view.RxToast;

import java.util.ArrayList;
import java.util.List;

import co.mobiwise.library.MusicPlayerView;

public class MusicPlayDialog extends Dialog implements View.OnClickListener {
    private TextView moneyEt;
    private TextView packageTypeTv;
    private ImageView closeIv;
    private TextView tipTv;
    private MusicPlayerView mpv;
    private LrcView mLrcView;
    private LinearLayout leftLl, rightLl;
    private DefaultLrcBuilder builder;
    private List<LrcRow> rows;
    //播放的是当前列表
    private static int playPosition = -1;
    private MusicService musicService;
    private ImageView minimizeIv;
    private boolean isError;
    private ImageView playType;

    public MusicPlayDialog(@NonNull Context context) {
        super(context);
    }

    private Context context;
    private int mLayoutResId;
    private int[] mIds = new int[0];
    private int mAnimationResId = 0;
    private OnCustomDialogItemClickListener listener;
    private boolean mIsDismiss = true;
    private boolean mIsDismissTouchOut = true;
    private int mPosition = 0;
    private List<View> mViews = new ArrayList();
    private MusicVo.DataBean musicVo;
    private String localPath;

    public void setOnDialogItemClickListener(OnCustomDialogItemClickListener listener) {
        this.listener = listener;
    }

    public MusicPlayDialog(Context context, MusicVo.DataBean musicVo, String localPath, int mPosition) {
        super(context, com.siberiadante.customdialoglib.R.style.Custom_Dialog_Style);
        this.context = context;
        this.musicVo = musicVo;
        this.localPath = localPath;
        if (mPosition >= 0) {
            this.playPosition = mPosition;
        }
    }

    public MusicPlayDialog(Context context, int layoutResID, double inte) {
        super(context, com.siberiadante.customdialoglib.R.style.Custom_Dialog_Style);
        this.context = context;
        this.mLayoutResId = layoutResID;
    }

    public MusicPlayDialog(Context context, int layoutResID, int[] listenedItems) {
        super(context, com.siberiadante.customdialoglib.R.style.Custom_Dialog_Style);
        this.context = context;
        this.mLayoutResId = layoutResID;
        this.mIds = listenedItems;
    }

    public MusicPlayDialog(Context context, int layoutResID, int[] listenedItems, int animationResId) {
        super(context, com.siberiadante.customdialoglib.R.style.Custom_Dialog_Style);
        this.context = context;
        this.mLayoutResId = layoutResID;
        this.mIds = listenedItems;
        this.mAnimationResId = animationResId;
    }

    public MusicPlayDialog(Context context, int layoutResID, int[] listenedItems, boolean isDismiss) {
        super(context, com.siberiadante.customdialoglib.R.style.Custom_Dialog_Style);
        this.context = context;
        this.mLayoutResId = layoutResID;
        this.mIds = listenedItems;
        this.mIsDismiss = isDismiss;
    }

    public MusicPlayDialog(Context context, int layoutResID, int[] listenedItems, boolean isDismiss, boolean isDismissTouchOut) {
        super(context, com.siberiadante.customdialoglib.R.style.Custom_Dialog_Style);
        this.context = context;
        this.mLayoutResId = layoutResID;
        this.mIds = listenedItems;
        this.mIsDismiss = isDismiss;
        this.mIsDismissTouchOut = isDismissTouchOut;
    }

    public MusicPlayDialog(Context context, int layoutResID, int[] listenedItems, boolean isDismiss, int position) {
        super(context, com.siberiadante.customdialoglib.R.style.Custom_Dialog_Style);
        this.context = context;
        this.mLayoutResId = layoutResID;
        this.mIds = listenedItems;
        this.mPosition = position;
    }

    public MusicPlayDialog(Context context, int layoutResID, int[] ids, int animationResId, boolean isDismiss, boolean isDismissTouchOut, int position) {
        super(context, com.siberiadante.customdialoglib.R.style.Custom_Dialog_Style);
        this.context = context;
        this.mLayoutResId = layoutResID;
        this.mIds = ids;
        this.mAnimationResId = animationResId;
        this.mIsDismiss = isDismiss;
        this.mIsDismissTouchOut = isDismissTouchOut;
        this.mPosition = position;
    }

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Window window = this.getWindow();
        if (0 == this.mPosition) {
            window.setGravity(17);
        } else {
            window.setGravity(this.mPosition);
        }

        window.setGravity(Gravity.BOTTOM);
        if (this.mAnimationResId == 0) {
            window.setWindowAnimations(com.siberiadante.customdialoglib.R.style.bottom_animation);
        } else {
            window.setWindowAnimations(this.mAnimationResId);
        }
        this.mLayoutResId = R.layout.dialog_music_play;
        this.setContentView(this.mLayoutResId);
        WindowManager windowManager = ((Activity) this.context).getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        WindowManager.LayoutParams lp = this.getWindow().getAttributes();
        lp.width = display.getWidth();
        this.getWindow().setAttributes(lp);
        this.setCanceledOnTouchOutside(this.mIsDismissTouchOut);
        int[] var6 = this.mIds;
        int var7 = var6.length;

        for (int var8 = 0; var8 < var7; ++var8) {
            int id = var6[var8];
            View view = this.findViewById(id);
            view.setOnClickListener(this);
            this.mViews.add(view);
        }
        playType = findViewById(R.id.play_type_iv);
        if (AppConstant.PLAY_TYPE == AppConstant.SINGLE_PLAY) {
            playType.setImageResource(R.mipmap.single_play);
        } else {
            playType.setImageResource(R.mipmap.loop_play);
        }
        playType.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (AppConstant.PLAY_TYPE == AppConstant.SINGLE_PLAY) {
                    playType.setImageResource(R.mipmap.loop_play);
                    AppConstant.PLAY_TYPE = AppConstant.LOOP_PLAY;
                } else {
                    playType.setImageResource(R.mipmap.single_play);
                    AppConstant.PLAY_TYPE = AppConstant.SINGLE_PLAY;
                }
                RxSPTool.putInt(context, "playType", AppConstant.PLAY_TYPE);
            }
        });
        tipTv = findViewById(R.id.name_tv);
        moneyEt = findViewById(R.id.author_tv);
        closeIv = findViewById(R.id.close_iv);
        closeIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
                RxKeyboardTool.hideSoftInput((Activity) context);
                MusicService.stopThis(context);
            }
        });
        minimizeIv = findViewById(R.id.minimize_iv);
        minimizeIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
                RxKeyboardTool.hideSoftInput((Activity) context);
            }
        });

        MusicService.startThis(context);
        musicService = new MusicService().newInstance();
        musicService.setOnMediaListener(new MusicService.OnMediaListener() {
            @Override
            public void onMediaPrepared(MediaPlayer mp) {
                mpv.setMax((int) (1.0 * mp.getDuration() / 1000));
                mpv.start();
                mpv.toggle();
                mpv.setProgress(mp.getCurrentPosition() / 1000);
            }

            @Override
            public void onMediaCompletion(MediaPlayer mp) {
                if (onSwitchListener != null) {
                    if (AppConstant.PLAY_TYPE == AppConstant.SINGLE_PLAY) {
//                        mpv.setMax((int) (1.0 * mp.getDuration() / 1000));
//                        mpv.start();
//                        mp.start();
                        musicService.singlePlay(musicVo,localPath,playPosition);
                    } else {
                        mpv.toggle();
                        onSwitchListener.onRight(playPosition);
                    }
                }
            }

            @Override
            public void onError() {
                RxToast.error("资源文件出问题，请去其他的网站重新搜索资源");
                isError = true;
                dismiss();
                RxKeyboardTool.hideSoftInput((Activity) context);
                MusicService.stopThis(context);
            }
        });
        musicService.setOnHandlerListener(new MusicService.OnHandlerListener() {
            @Override
            public void handlerMsg(MediaPlayer mp) {
                if (isError) {
                    return;
                }
                if (mpv.isRotating()) {
                    //播放器播放时，时间更新后调用这个时歌词数据更新到当前对应的歌词，播放器一般时间更新以秒为频率更新
                    long time = mp.getCurrentPosition();
                    mLrcView.seekLrcToTime(time);
                }
            }
        });
        mpv = findViewById(R.id.mpv);
        mpv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isError) {
                    return;
                }
//                isError = false;
                if (mpv.isRotating()) {
                    mpv.stop();
                    musicService.getMediaPlayer().pause();
                } else {
                    mpv.start();
                    musicService.getMediaPlayer().start();
                }
            }
        });
        //歌词
//        String lrcPath = MyUtil.getAppMusicPath() + "/" + musicVo.getTitle() + "~" + musicVo.getAuthor() + ".lrc";
        mLrcView = findViewById(R.id.lrc_view);
        mLrcView.setListener(new ILrcViewListener() {
            @Override
            public void onLrcSeeked(int newPosition, LrcRow row) {
                if (isError) {
                    return;
                }
                mpv.setProgress((int) row.time / 1000);
                musicService.getMediaPlayer().seekTo((int) row.time);
            }
        });
        rightLl = findViewById(R.id.right_ll);
        rightLl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isError) {
                    return;
                }
                if (onSwitchListener != null) {
                    if (musicService.getMediaPlayer().isPlaying()) {
                        mpv.toggle();
                    }
                    musicService.getMediaPlayer().stop();
                    mpv.stop();
                    onSwitchListener.onRight(playPosition);
                }
            }
        });
        leftLl = findViewById(R.id.left_ll);
        leftLl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isError) {
                    return;
                }
                if (onSwitchListener != null) {
                    if (musicService.getMediaPlayer().isPlaying()) {
                        mpv.toggle();
                    }
                    musicService.getMediaPlayer().stop();
                    mpv.stop();
                    onSwitchListener.onLeft(playPosition);
                }
            }
        });
        resetMusic(musicVo, localPath, playPosition);
    }

    public void resetMusic(MusicVo.DataBean dataBean, String localPath, int playPosition) {
        this.playPosition = playPosition;
        this.musicVo = dataBean;
        this.localPath = localPath;
        musicService.resetMusic(dataBean, localPath, playPosition);
        tipTv.setText(dataBean.getTitle());
        moneyEt.setText(dataBean.getAuthor());
        mpv.setButtonColor(Color.DKGRAY);
        if (!RxDataTool.isEmpty(musicVo.getPic())) {
            mpv.setCoverURL(musicVo.getPic());
        }
        mpv.setProgressEmptyColor(Color.GRAY);
        mpv.setProgressLoadedColor(context.getResources().getColor(R.color.colorAccent));
        mpv.setTimeColor(Color.WHITE);
        //解析歌词构造器
        builder = new DefaultLrcBuilder();
        //解析歌词返回LrcRow集合
        rows = builder.getLrcRows(musicVo.getLrc());
        //将得到的歌词集合传给mLrcView用来展示
        mLrcView.setLrc(rows);
    }

    private OnSwitchListener onSwitchListener;

    public void setOnSwitchListener(OnSwitchListener onSwitchListener) {
        this.onSwitchListener = onSwitchListener;
    }

    public interface OnSwitchListener {
        void onLeft(int position);  //下一曲

        void onRight(int position); //上一曲
    }

    @Override
    public void dismiss() {
        super.dismiss();
        if (mpv != null) {
            mpv.stop();
        }
        MyUtil.musicPlayDialog = null;
    }

    public List<View> getViews() {
        return this.mViews;
    }

    public void onProvideKeyboardShortcuts(List<KeyboardShortcutGroup> data, @Nullable Menu menu, int deviceId) {
    }

    public void onClick(View view) {
        if (this.mIsDismiss) {
            this.dismiss();
        }

        this.listener.OnCustomDialogItemClick(this, view);
    }

    public interface OnCustomDialogItemClickListener {
        void OnCustomDialogItemClick(MusicPlayDialog var1, View var2);
    }
}
